package com.rpp.config;

import com.rpp.enums.NodeType;
import com.rpp.enums.SqlCommandType;
import com.rpp.pojo.Configuration;
import com.rpp.pojo.MapedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuider {

    private Configuration configuration;

    public XmlMapperBuider(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document read = new SAXReader().read(inputStream);
        Element rootElement = read.getRootElement();
        String namespace = rootElement.attributeValue("nameSpace");
        this.parse(namespace, "select", rootElement);
        this.parse(namespace, "insert", rootElement);
        this.parse(namespace, "update", rootElement);
        this.parse(namespace, "delete", rootElement);
    }

    private void parse(String namespace, String nodeType, Element rootElement) {
        SqlCommandType sqlCommandType;
        NodeType type = NodeType.parse(nodeType);
        switch (type) {
            case SELECT: {
                sqlCommandType = SqlCommandType.SELECT;
                break;
            }
            case INSERT: {
                sqlCommandType = SqlCommandType.INSERT;
                break;
            }
            case UPDATE: {
                sqlCommandType = SqlCommandType.UPDATE;
                break;
            }
            case DELETE: {
                sqlCommandType = SqlCommandType.DELETE;
                break;
            }
            default:
                sqlCommandType = SqlCommandType.UNKNOWN;
        }
        List<Element> list = rootElement.selectNodes("//" + nodeType);
        for (Element element : list) {
            MapedStatement mapedStatement = new MapedStatement();
            String id = element.attributeValue("id");
            String resurnType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getText();
            mapedStatement.setId(id);
            mapedStatement.setSqlText(sql);
            mapedStatement.setResultType(resurnType);
            mapedStatement.setParamterType(paramterType);
            mapedStatement.setSqlCommandType(sqlCommandType);

            String key = namespace + "." + id;

            configuration.getMapedStatementMap().put(key, mapedStatement);
        }
    }
}
